

import { isProduction, platform } from '../../utils/check'
import { versionInfo } from '../../utils/common';
import { fetchUserData } from '../../utils/user';

type GTagType = 'config' | 'event'
type GMap = { [key: string]: string | number | boolean | undefined };

type GTagParmasType = {
    type: GTagType,
    name: string,
    params?: GMap
}

class GoogleAnalytics {
    // private src = 'https://www.googletagmanager.com/gtag/js?id=G-9JF0XFN2WH'
    // private id = 'google_analytics'
    private cache: GTagParmasType[] = [];
    private gtag?: (...args: any[]) => void;
    private userId?: string;
    private os?: string;
    private version?: string;
    constructor(os: string) {
        if (!isProduction()) {
            console.debug('no google analytics')
            return
        }

        this.os = os;
        this.version = versionInfo();

        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        this.gtag = window.gtag
        this.gtag?.('js', new Date());
        // this.gtag('config', 'G-9JF0XFN2WH');
        this.gtag?.('set', {
            os,
            version: this.version
        })

        try {
            setTimeout(() => {
                const user = fetchUserData();
                if (user?.customerId) {
                    this.configUser(user.customerId)
                }
            }, 0);
        } catch (error) {
            console.error(error)
            // temp
        }
    }

    private tagCache() {
        if (this.cache.length && this.gtag) {
            while (this.cache.length) {
                const item = this.cache.shift();
                item && this.gtag(item.type, item.name, item.params)
            }
        }
    }

    private defaultInfo() {
        return {
            os: this.os,
            version: this.version,
            player_id: this.userId
        }
    }

    private markpoint(type: 'config' | 'event', name: string, params?: { [key: string]: string | number | boolean | undefined }) {
        if (!this.gtag) {
            this.cache.push({
                type,
                name,
                params
            })
            return
        }
        this.tagCache();
        this.gtag?.(type, name, params)
    }

    public configUser = (userId: string) => {
        if (!userId) {
            return
        }

        if (userId === this.userId) {
            return
        }

        this.userId = userId;
        this.markpoint('config', 'G-9JF0XFN2WH', {
            user_id: userId
        })
    }

    public event = (name: string, params?: { [key: string]: string | number | boolean }) => {
        try {
            this.markpoint('event', name, { ...params, ...this.defaultInfo() })
        } catch (error) {
            // temp
        }
    }

    public hasConfig() {
        return Boolean(this.userId?.length)
    }
}

const gtag = new GoogleAnalytics(platform())
export default gtag;
